<?php
namespace Admin\Controller;
use Admin\Common\Page;
class BagstoryController extends BaseController
{
    /**
     * 书包库
     */
    public function index()
    {
        $bag = M('bag');
        $key = I('get.keywords');
        if($key != ""){
            $map = " and bag_card like '%{$key}%'";
        }else{
            $map = "";
        }
        $count = $bag ->where("status=0".$map)->count();
        $Page = new  Page($count , C('page.size'));// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show = $Page->show();// 分页显示输出
        $this->assign('page' , $show);// 赋值分页输出
        $bagdata = $bag->where("status=0".$map)->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $this->assign('bagdata',$bagdata);
        $this->display();

    }
    /**
     * 创建书包
     */
    public function add(){

        if(IS_POST){
            $db = M();
            $db->startTrans();
            $data = I('post.');
            unset($_POST['code']);
            if($data['bag_name'] == null){
                $this->error('书包名称不能为空');
            }
            if(count($data['code']) == 0){
                $this->error('至少有一个书的条码');
            }else{
                $bag_id = $db->table('bag')->data($_POST)->add();

                foreach($data['code'] as $k=>$v){
                    $book = D('book')->where("tm='{$v}'")->find();
                    if($book){
                        $arr= [
                            'book_id' => $book['book_id'],
                            'bag_id' => $bag_id,
                        ];

                        /**
                         * 修改图书库存数量
                         */
                        $ids = [$book['book_id']];
                        $link = D('book')->bookStatus($ids,1);
                        if($link == 400){
                            $db->rollback();
                            $this->error('修改图书库存出错,图书ID为:'.$book['book_id']);
                        }
                        $db->table('bag_book')->add($arr);
                    }else{
                       $db->rollback();

                        $this->error('图书条码:'.$v.'不存在;第'.($k+1).'个图书条码');
                    }
                }
                $link->commit();
                $db->commit();
                $this->success('创建成功',U('index'));
            }


            $this->error('创建失败');
        }else{
            $bag_card = D('bag')->order('bag_id desc')->select()['0']['bag_card'];
            if($bag_card == null){
                $bag_card = '150000';
            }else{
                $bag_card++;
            }
            $this->assign('bag_card',$bag_card);
            $this->display();
        }
    }
    /**
     * 修改书包
     */
    public function edit(){
             $bag_id = I('get.bag_id');
            // $bag_data  = M('bag')->select();
             $bag_data = M('bag')->where("bag_id=$bag_id")->find();
             $this->assign('bag_data',$bag_data);
 //            $this->assign('data',$data);
             $this->display();


        }
    /**
     * do 修改书包
     */
    public function doedit(){
        $bag_id = I('get.bag_id');
        $data= I('post.');
      //  $data['childschool_id'] = I('post.childschool_id');
        $res = M('bag')->where("bag_id =$bag_id")->data($data)->save();
        if($res !==false){
            $this->success('修改成功',U('index'));

        }else{
            $this->error('修改失败');

        }



    }


    /**
     * 删除书包
     */
    public function del(){
        $bag_id=I('get.bag_id');
        // TODO  要先判断是不是空书包（还没实现）
        $db = M();
        $db->startTrans();
        $data = ['status'=>4];
        $map = [
            'status' => 0,
            'bag_id' => $bag_id
        ];
        $res1 = $db->table('bag')->where("bag_id=$bag_id")->save($data);
        $bookIds = $db->table('bag_book')->where($map)->getField('book_id',true);
        if(count($bookIds)){
            $db->table('bag_book')->where($map)->save($data);
            /*修改图书库存*/
            $link = D('book')->bookStatus($bookIds,2);
            if($link == 400){
                $db->rollback();
                $this->error('修改库存失败');
            }
        }
        if($res1){
            if(count($bookIds)){
                $link->commit();
            }
            $db->commit();
            $this->success('删除成功',U("index"));
        }else{
            $db->rollback();
            $this->error('删除失败');
        }

    }







    /**
     * 图书列表
     */
    public function booklist()
    {
        $db = M();
        $count = $db->table('bag_book')->where(I('get.'))->count();
        $Page = new  Page($count , C('page.size'));// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show = $Page->show();// 分页显示输出
        $this->assign('page' , $show);// 赋值分页输出

        $bookData = $db->table('bag_book as a,book as b,bag as c')
            ->field('a.*,c.bag_name,b.sm,b.tm,b.book_id')
            ->where("a.bag_id=".I('get.bag_id')." and a.bag_id=c.bag_id and a.book_id=b.book_id and a.status=0")
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();
        $this->assign('classdata',$bookData);
        $this->display();

    }

    /**
     * 书包库添加图书
     */
    public function addBook(){
        $db = M();
        if(IS_POST){
            $db->startTrans();
            $bag_id = I('post.bag_id');
            $data = I('post.code');
            foreach($data as $k=>$v){
                $book = D('book')->where("tm='{$v}'")->find();
                if($book){
                    $arr= [
                        'book_id' => $book['book_id'],
                        'bag_id' => $bag_id,
                    ];
                    $db->table('bag_book')->add($arr);
                    /*图书库存修改*/
                    $link = D('book')->bookStatus(array($book['book_id']),1);
                    if($link == 400){
                        $db->rollback();
                        $this->error('修改图书库存失败,图书ID为:'.$book['book_id']);
                    }
                }else{
                    $db->rollback();

                    $this->error('图书条码:'.$v.'不存在;第'.($k+1).'个图书条码');
                }
            }
            $link->commit();
            $db->commit();
            $this->success('添加成功',U('booklist',array('bag_id'=>$bag_id)));
        }else{
            $bag_id = I('get.bag_id');
            if($bag_id == null){
                $this->error('参数错误');
            }else{
                $bag = $db->table('bag')->where(I('get.'))->find();
                $this->assign('bag',$bag);
            }
            $this->display();
        }
    }

    /**
     * 删除图书
     */
    public function delBook(){
        if(is_null(I('get.id')) || is_null(I('get.bag_id'))){
          $this->error('参数错误');
        }
        $data = ['status'=>4];
        $db = M();
        $db->startTrans();
        $id = $db->table('bag_book')->where('id='.I('get.id'))->getField('book_id');
        /*修改图书库存*/
        $link = D('book')->bookStatus(array($id),2);
        if($link == 400){
            $this->error('修改图书库存失败,图书ID为:'.$id);
        }
        $res = $db->table('bag_book')->where('id='.I('get.id'))->save($data);
        if($res){
            $db->commit();
            $link->commit();
            $this->success('删除成功',U('booklist',array('bag_id'=>I('get.bag_id'))));
        }else{
            $db->rollback();
            $this->error('删除失败');
        }
    }

    /**
     * 替换图书
     */
    public function replaceBook(){
        $db = M();
        if(IS_POST){
            $db->startTrans();
            //dump($_POST);die;
            $data['status'] = 4;
            $key1 = $db->table('bag_book')->where('id='.I('post.bag_book_id'))->save($data);
            $ids = $db->table('bag_book')->where('id='.I('post.bag_book_id'))->getField('book_id');
            $link1 = D('book')->bookStatus(array($ids),2);
            if($link1 == 400){
                $db->rollback();
                $this->error('旧图书修改库存失败');
            }
            $book = D('book')->where("tm='".I('post.tm')."'")->find();
            if($book){
                $arr= [
                    'book_id' => $book['book_id'],
                    'bag_id' => I('post.bag_id'),
                ];
                /*还未做出图书状态修改  原先未有该功能*/
                $key2 = $db->table('bag_book')->add($arr);
                $link2 = D('book')->bookStatus(array($book['book_id']),1);
                if($link2 == 400){
                    $db->rollback();
                    $this->error('新图书修改库存失败');
                }

            }else{
                $db->rollback();

                $this->error('图书条码:'.I('post.tm').'不存在');
            }
            if($key1 && $key2){
                $link1->commit();
                $link2->commit();
                $db->commit();
                $this->success('替换成功',U('booklist',array('bag_id'=>I('post.bag_id'))));
            }else{
                $db->rollback();
                $this->error('替换失败');
            }

        }else{
            $sm = D('book')->where('book_id='.I('get.book_id'))->getField('sm');
            $this->assign('sm',$sm);
            $this->display();
        }
    }


    /**
     * 绑定学生
     */
    public function bind(){
        if(IS_POST){
            /*首先查询有没有该学生*/
            $db = M();
            $db->startTrans();
            if(!is_numeric(I('post.card_id'))){
                $this->error('会员卡号必须是数字');
            }
            $stu = $db->table('student')->where('status=0 and card_id='.I('post.card_id'))->find();
            if($stu){
                if($stu['status'] == 1){
                    $this->error('当前学生已有书包,请先将该学生书包解绑');
                }
                /*先将书包状态修改*/
                $key = $db->table('bag')->where('bag_id='.I('post.bag_id'))->save(array(
                    'stu_id' => $stu['stu_id'],
                    'status' => 1  //0为 未绑定 1 为绑定
                ));
                /*修改学生状态*/
                $stu['status'] = 1;
                $stu['bag_id'] = I('post.bag_id');
                $key1 = $db->table('student')->where('stu_id='.$stu['stu_id'])->save($stu);
                /*修改书的状态*/
                $ids = $db->table('bag_book')->where('status=0 and bag_id='.I('post.bag_id'))->getField('book_id',true);
                if(count($ids)){
                    $link = D('book')->bookStatus($ids,3);
                }
                /*添加历史记录*/
                $bag = $db->table('bag')->where('bag_id='.I('post.bag_id'))->find();
                $bookData = $db->table('bag_book as a,book as b')->where('a.book_id=b.book_id and a.status=0 and a.bag_id='.$bag['bag_id'])->field('b.sm')->select();
                $bookName = array();
                foreach ($bookData as $k => $v){
                    $bookName[]=$v['sm'];
                }
                $bookName = trim(implode('、',$bookName),'、');

                $bookTmData = $db->table('bag_book as a,book as b')->where('a.book_id=b.book_id and a.status=0 and a.bag_id='.$bag['bag_id'])->field('b.tm')->select();
                $bookTm = array();
                foreach ($bookTmData as $k => $v){
                    $bookTm[]=$v['tm'];
                }
                $bookTm = trim(implode('、',$bookTm),'、');

                $db->table('bag_log')->add(array(
                    'user_id' => $stu['user_id'],
                    'card_id' => $stu['card_id'],
                    'bag_id' => $bag['bag_id'],
                    'bag_card' => $bag['bag_card'],
                    'created_at' => time(),
                    'book_names' => $bookName,
                    'book_tm' => $bookTm
                ));

                if($link == 400){
                    $db->rollback();
                    $this->error('修改图书库存时出错');
                }
                if($key && $key1){
                    if(count($ids)){
                        $link->commit();
                    }
                    $db->commit();
                    $this->success('绑定成功',U('bag/index'));
                }else{
                    $db->rollback();
                    $this->error('绑定失败');
                }
            }else{
                $this->error('该会员卡号并没有绑定班级,请先去绑定班级后继续操作(或没有该会员)');
            }
        }else{
            $bag_id = I('get.bag_id');
            if($bag_id == ""){
                $this->error('参数错误');
            }
            $bag = D('bag')->where('bag_id='.$bag_id)->find();
            $this->assign('bag',$bag);
            $this->display();
        }
    }

}
